import urllib
from urllib import request,parse
import json

# POST请求的目标URL
#有道翻译
def youdao():
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule";
    headers={"User-Agent": "Mozilla...."};
    content=input("请输入要翻译的文字：");
    if content=="ESC":
        print("翻译到此结束！")
        return
    else:
        formdata = {
            "action":"FY_BY_REALTIME",
            "client":"fanyideskweb",
            "doctype":"json",
            "from":"AUTO",
            "i":content,
            "keyfrom":"fanyi.web",
            "salt":"1541727805306",
            "sign":"eff7e5dcb3dc06079a25486c5820fe8f",
            "smartresult":"dict",
            "to":"AUTO",
            "typoResult":"false",
            "version":"2.1"
        };
        data = parse.urlencode(formdata).encode("utf-8");
        re =request.Request(url, data = data, headers = headers);
        res= request.urlopen(re);
        buff=res.read();
        html=buff.decode("utf-8");
        #把json转换成python类型
        result_dict = json.loads(html);
        src=result_dict["translateResult"][0][0]["src"];
        res=result_dict["translateResult"][0][0]["tgt"];
        print(src+"翻译成英语为："+res);
        youdao();

youdao();
